package cn.js.sangu.unitStore.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.StrUtil;
import cn.js.sangu.unitStore.common.LogType;
import cn.js.sangu.unitStore.common.MyAuthAccess;
import cn.js.sangu.unitStore.common.MyLogsAOP;
import cn.js.sangu.unitStore.common.R;
import cn.js.sangu.unitStore.common.config.MyAppConfig;
import cn.js.sangu.unitStore.entity.FileNas;
import cn.js.sangu.unitStore.entity.User;
import cn.js.sangu.unitStore.service.FileService;
import cn.js.sangu.unitStore.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import lombok.extern.slf4j.Slf4j;

/**
 * 说明：
 * 作者：linshuo
 * 日期：2024/8/11 12:45
 */
// 导入SLF4J的日志注解和日志工厂类
@Slf4j
@RestController
@RequestMapping("file")
public class FileController {

    static final String OPERATION_FILE = "文件模块";

//    @Value("${system.ip:localhost}")
//    String ip;

//    @Value("${server.port}")
//    String port;

    @Autowired
    MyAppConfig myAppConfig;

    @Autowired
    FileService fileService;

    @Autowired
    UserService userService;

//    @MyAuthAccess
    @PostMapping("upload")
    public R upload(MultipartFile file) throws IOException {
        return R.ok(fileService.upload(file));
    }

    @MyAuthAccess
    @GetMapping("download/{id}/{today}/{fileName}")
    public void download(@PathVariable Integer id,
                         @PathVariable String today,
                         @PathVariable String fileName,
                         HttpServletResponse response) throws IOException {
        //文件默认预览，可改为附件下载方式
//        response.addHeader("Content-Disposition","attachment;filename=" + URLEncoder.encode(fileName,"UTF-8"));
        //预览方式
        response.addHeader("Content-Disposition","inLine;filename=" + URLEncoder.encode(fileName,"UTF-8"));

        String fullRootPath = fileService.download(0,today,fileName);
        if (!FileUtil.exist(fullRootPath)) return;

        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(FileUtil.readBytes(fullRootPath));   //文件的字节流数组
        outputStream.flush(); //刷出去
        outputStream.close(); //关闭文件流
    }

    /**
     * 根据id和类型下载或预览
     * @param id
     * @param type
     * @param response
     * @throws IOException
     */
    @MyAuthAccess
    @GetMapping("download")
    public void download(
            @RequestParam(required = false) Integer id,
            @RequestParam(required = false) String type,
            HttpServletResponse response) throws IOException {
        FileNas fileNas = fileService.download(id);
        String fullRootPath = fileNas.getFilePath();
        String fileName = fileNas.getFileName();
        if (!FileUtil.exist(fullRootPath)) return;
        if ("preview".equals(type)){
            //预览方式
            response.addHeader("Content-Disposition","inLine;filename=" + URLEncoder.encode(fileName,"UTF-8"));
        }else if ("attachment".equals(type)){
            //文件默认预览，可改为附件下载方式
            response.addHeader("Content-Disposition","attachment;filename=" + URLEncoder.encode(fileName,"UTF-8"));
        }else {
            response.addHeader("Content-Disposition","inLine;filename=" + URLEncoder.encode(fileName,"UTF-8"));
            response.addHeader("Content-Disposition","attachment;filename=" + URLEncoder.encode(fileName,"UTF-8"));
        }
        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(FileUtil.readBytes(fullRootPath));   //文件的字节流数组
        outputStream.flush(); //刷出去
        outputStream.close(); //关闭文件流
    }

    /**
     * 从Common根据文件名下载
     * @param fileName
     * @param response
     * @throws IOException
     */
    @MyAuthAccess
    @GetMapping("download/{fileName}")
    public void download(@PathVariable String fileName,HttpServletResponse response) throws IOException {
        if (StrUtil.isNotBlank(fileName)){
            String filePath = fileService.download(0, "common", fileName);
            if (!FileUtil.exist(filePath)) {
                log.warn("文件不存在：{}",filePath);
                return;
            }
            ServletOutputStream outputStream = response.getOutputStream();
            outputStream.write(FileUtil.readBytes(filePath));   //文件的字节流数组
            outputStream.flush(); //刷出去
            outputStream.close(); //关闭文件流
        }
//        if ("head.png".equals(fileName)){
//            FileNas fileNas = fileService.download(418);
//            String filePath = fileNas.getFilePath();
//            if (!FileUtil.exist(filePath)) return;
//            ServletOutputStream outputStream = response.getOutputStream();
//            outputStream.write(FileUtil.readBytes(filePath));   //文件的字节流数组
//            outputStream.flush(); //刷出去
//            outputStream.close(); //关闭文件流
//        }
    }

    @PostMapping("editor/upload")
    public Dict editorUpload(@RequestParam MultipartFile file,@RequestParam String type) throws IOException {
        Object data = null;
        if ("img".equals(type)){
            data = CollUtil.newArrayList(Dict.create().set("url", this.upload(file).getData()));
        }else if ("video".equals(type)){
            data = Dict.create().set("url",this.upload(file).getData());
        }
        return Dict.create().set("errno",0).set("data", data);
    }

    @MyLogsAOP(operation = OPERATION_FILE,operaType = LogType.LOOKUP)
    @GetMapping("findByPage")
    public R findByPage(
            @RequestParam Integer pageNum,
            @RequestParam Integer pageSize,
            @RequestParam String fileName,
            @RequestParam String creator){
        QueryWrapper<FileNas> wrapper = new QueryWrapper<>();
        wrapper.like(StrUtil.isNotBlank(fileName),"file_name",fileName);
        wrapper.eq(StrUtil.isNotBlank(creator),"user_id",creator);
        wrapper.orderByDesc("id");
        //构建page对象
        Page<FileNas> param = new Page<>(pageNum, pageSize);
        Page<FileNas> res = fileService.page(param, wrapper);
        return R.ok(res.setRecords(this.suppleName(res.getRecords())));
    }

    /**
     * 补充作者和修改人名称
     */
    private List<FileNas> suppleName(List<FileNas> list ){
        for (FileNas item : list) {
            //作者
            User author = userService.getById(item.getUserId());
            if (null != author) item.setUsername(author.getName());
            //修改人
            User modifier = userService.getById(item.getModifier());
            if (null != modifier) item.setModifierName(modifier.getName());
        }
        return list;
    }


}
